# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import requests
import time

from absl import app, flags

import pandas
import matplotlib
matplotlib.use('Agg')

FLAGS = flags.FLAGS


def query_bitmex_xbtusd_funding_rate_history(start: int, count=200):
  try:
    xbtusd_funding_url = (
        'https://www.bitmex.com/api/v1/funding?symbol=XBTUSD&count=%d&start=%d&reverse=false' %
        (count, start))
    content = requests.get(xbtusd_funding_url).content
    df = pandas.read_json(content)
    return df
  except requests.HTTPError as e:
    print(e)


def query_funding_history():
  funding_rate_df = pandas.DataFrame()
  start = 0
  while True:
    df = query_bitmex_xbtusd_funding_rate_history(start)
    funding_rate_df = pandas.concat([funding_rate_df, df])
    start += 200
    if len(df) < 200:
      break
    time.sleep(1)

  return funding_rate_df


def main(argv):
  csv_path = FLAGS.csv_out_path
  assert csv_path, '--csv_out_path must be specified.'

  funding_rate_df = query_funding_history()
  print(funding_rate_df.to_string())
  funding_rate_df.to_csv(csv_path, index=False)

  return 0


if __name__ == '__main__':
  flags.DEFINE_string('csv_out_path', None, 'Output csv file path.')

  app.run(main)
